/**
 * Copyright (c) 2004-2017 All Rights Reserved.
 */
package com.zbest.common.lang.serialize;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import com.caucho.hessian.io.HessianSerializerInput;
import com.caucho.hessian.io.HessianSerializerOutput;

/**
 * 
 *
 * @author czhou3306@gmail.com
 * @version $Id: HessianSerializeUtil.java, v0.1 2017年3月23日 上午10:48:45 czhou3306@gmail.com Exp $
 */
public class HessianSerializeUtil {
    /**
    *
    * 纯hessian序列化
    *
    * @param <T>
    *
    * @param object
    *
    * @return
    *
    * @throws Exception
    */

    public static <T> byte[] serialize(T object) {
        if (object == null) {
            throw new NullPointerException();
        }
        byte[] results = null;
        ByteArrayOutputStream os = null;
        HessianSerializerOutput hessianOutput = null;
        try {
            os = new ByteArrayOutputStream();
            hessianOutput = new HessianSerializerOutput(os);
            //write本身是线程安全的
            hessianOutput.writeObject(object);
            os.close();
            results = os.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (os != null)
                    os.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return results;
    }

    /**
    *
    * 纯hessian反序列化
    *
    * @param bytes
    *
    * @return
    *
    * @throws Exception
    */

    @SuppressWarnings("unchecked")
    public static <T> T deserialize(byte[] bytes) {
        if (bytes == null) {
            throw new NullPointerException();
        }
        T result = null;
        ByteArrayInputStream is = null;
        try {
            is = new ByteArrayInputStream(bytes);
            HessianSerializerInput hessianInput = new HessianSerializerInput(is);
            result = (T) hessianInput.readObject();

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return result;

    }
}
